package com.hboxs.asl.controller.asl.member;

import com.hboxs.asl.JsonMessage;
import com.hboxs.asl.controller.asl.BaseController;
import com.hboxs.asl.entity.Coupon;
import com.hboxs.asl.entity.CouponCode;
import com.hboxs.asl.entity.Member;
import com.hboxs.asl.service.CouponCodeService;
import com.hboxs.asl.service.CouponService;
import com.hboxs.asl.service.MemberService;
import com.hboxs.asl.service.MessageService;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.List;


@Controller("aslMemberCouponController")
@RequestMapping("/weChat/coupon")
public class CouponController extends BaseController {

    protected Logger logger = Logger.getLogger(getClass());

    @Resource(name = "memberServiceImpl")
    private MemberService memberService;
    @Resource(name = "couponServiceImpl")
    private CouponService couponService;
    @Resource(name = "couponCodeServiceImpl")
    private CouponCodeService couponCodeService;
    @Resource(name = "messageServiceImpl")
    private MessageService messageService;


    /**
     * 获取当前用户可领取优惠卷列表
     * 排除以下情况:(1)用户已经领取且领取次数达到上限.(2)优惠券已过期
     *
     * @return 优惠卷列表
     */
    @RequestMapping(value = "/opening", method = RequestMethod.GET)
    public String openingCoupons(ModelMap modelMap) {
        try {
            Member member = memberService.getCurrent();
            modelMap.addAttribute("coupons", couponService.findReceivableCoupons(member));
            return "/yijing/coupon-anarchy";
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return "/404.html";
    }

    /**
     * 领取优惠卷
     *
     * @param id 购物卷id
     * @return json
     */
    @RequestMapping(value = "/receive", method = RequestMethod.POST)
    public
    @ResponseBody
    Object receive(Long id) {

        try {
            Member member = memberService.getCurrent();
            if (member == null) {
                return JsonMessage.USER_NOT_LOGIN;
            }

            Coupon coupon = couponService.find(id);
            if (coupon == null) {
                return JsonMessage.error("优惠券不存在");
            }
            Long num = couponService.findReceivableCount4Coupon(member, coupon);
            if (num > 0) {
                couponCodeService.build(coupon, member);
            }
            if (num - 1 > 0) {
                messageService.addMessage(memberService.getCurrentByToken(), "领取成功", "恭喜成功领取优惠券【"+coupon.getName()+"】");
                return JsonMessage.success("领取成功，您还有 " + (num - 1) + " 次领取机会！");
            } else {
                return JsonMessage.error("已无领取次数");
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonMessage.UNKNOWN_ERROR;
    }

    /**
     * 获取未使用的优惠券
     *
     * @param modelMap
     * @return
     */
    @RequestMapping(value = "/unused", method = RequestMethod.GET)
    public String unusedCoupons(ModelMap modelMap) {
        try {
            Member member = memberService.getCurrent();
            modelMap.addAttribute("style", "unused");
            modelMap.addAttribute("content", couponCodeService.findUnusedCouponCodes(member));
            modelMap.addAttribute("unusedCount", couponCodeService.countUnusedCouponCodes(member));
            modelMap.addAttribute("usedCount", couponCodeService.countUsedCouponCodes(member));
            modelMap.addAttribute("expireCount", couponCodeService.countOverdueCouponCodes(member));
            return "/yijing/my-coupon";
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return "/404.html";
    }

    /**
     * 获取已经使用的优惠券
     *
     * @param modelMap
     * @return
     */
    @RequestMapping(value = "/used", method = RequestMethod.GET)
    public String usedCoupons(ModelMap modelMap) {
        try {
            Member member = memberService.getCurrent();
            modelMap.addAttribute("style", "used");
            modelMap.addAttribute("content", couponCodeService.findUsedCouponCodes(member));
            modelMap.addAttribute("unusedCount", couponCodeService.countUnusedCouponCodes(member));
            modelMap.addAttribute("usedCount", couponCodeService.countUsedCouponCodes(member));
            modelMap.addAttribute("expireCount", couponCodeService.countOverdueCouponCodes(member));
            return "/yijing/my-coupon";
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return "/404.html";
    }

    /**
     * 获取过期的优惠券
     *
     * @param modelMap
     * @return
     */
    @RequestMapping(value = "/overdue", method = RequestMethod.GET)
    public String overdueCoupons(ModelMap modelMap) {
        try {
            Member member = memberService.getCurrent();
            modelMap.addAttribute("style", "overdue");
            modelMap.addAttribute("content", couponCodeService.findOverdueCouponCodes(member));
            modelMap.addAttribute("unusedCount", couponCodeService.countUnusedCouponCodes(member));
            modelMap.addAttribute("usedCount", couponCodeService.countUsedCouponCodes(member));
            modelMap.addAttribute("expireCount", couponCodeService.countOverdueCouponCodes(member));
            return "/yijing/my-coupon";
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return "/404.html";
    }

    /**
     * @param status
     * @return
     */
    @RequestMapping(value = "/changeCoupons", method = RequestMethod.GET)
    public
    @ResponseBody
    JsonMessage coupons(Integer status) {
        try {
            Member member = memberService.getCurrent();

            if (status != null && (0 <= status && status <= 2)) {
                List<CouponCode> couponCodes = null;
                switch (status) {
                    case 0:
                        couponCodes = couponCodeService.findUnusedCouponCodes(member);
                        break;
                    case 1:
                        couponCodes = couponCodeService.findUsedCouponCodes(member);
                        break;
                    case 2:
                        couponCodes = couponCodeService.findOverdueCouponCodes(member);
                        break;
                }
                return JsonMessage.success(JsonMessage.optimiseObj(couponCodes, "coupon.cut", "coupon.maximumPrice", "coupon.endDate"));
            } else {
                return JsonMessage.error("请求数据错误!");
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonMessage.UNKNOWN_ERROR;
    }

    /**
     * @param id
     * @param modelMap
     * @return
     */
    @RequestMapping(value = "/detail", method = RequestMethod.GET)
    public
    @ResponseBody
    Object detail(Long id, ModelMap modelMap) {
        CouponCode couponCode = couponCodeService.find(id);
        return JsonMessage.success(
                "couponCode",
                JsonMessage.optimiseObj(couponCode, "code"),
                "coupon",
                JsonMessage.optimiseObj(couponCode.getCoupon(), "id", "name", "cut")
        );

    }

}
